package my.assistant.reminder;

import java.util.Calendar;

import my.assistant.R;
import my.assistant.util.Constants;
import my.assistant.util.ReminderUtils;
import my.assistant.util.ResKey;
import my.assistant.util.ResUtils;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

public class ReminderService extends Service
{
	private static MediaPlayer mediaPlayer;
	private Intent alertIntent;
	private AlarmManager alarmManager;
	private Calendar cal = Calendar.getInstance();

	@Override
	public void onCreate()
	{
		if (mediaPlayer == null)
        {
	        mediaPlayer = new MediaPlayer();
        }
		alertIntent = new Intent(this, AlarmReceiver.class);
		alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
		Log.e("-------", " player :: " + mediaPlayer.hashCode() + ", this :: " + this.hashCode());
		if (ResUtils.hasKeyPrefix(ResKey.REMINDVO_PREFIX))
		{
			RemindVO vo;
			int n = 0;
			int count = 0;
			while (ResUtils.hasKeyPrefix(ResKey.REMINDVO_PREFIX + n))
			{
				vo = ReminderUtils.buildReminderVO(n);
				startService(vo, n);
				n++;
				count++;
			}
			while (count == 0 && n < Constants.MAX_REMINDER_COUNT)
			{
				n++;
				while (ResUtils.hasKeyPrefix(ResKey.REMINDVO_PREFIX + n))
				{
					vo = ReminderUtils.buildReminderVO(n);
					startService(vo, n);
					n++;
					count++;
				}
			}
		}
		Toast.makeText(this, R.string.reminder_service_started, Toast.LENGTH_SHORT).show();
	}

	private void startService(RemindVO vo, int n)
	{
		if (vo.enable)
		{
			PendingIntent operator = PendingIntent.getBroadcast(this, n, alertIntent, n);
			Constants.ALERT_SENDER_MAP.put(String.valueOf(n), operator);
			alarmManager.cancel(operator);
			vo.calculateAlarmTime(cal);
			alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, vo.alarmTime, operator);
		}
	}

	@Override
	public void onDestroy()
	{
		if (mediaPlayer.isPlaying())
		{
			mediaPlayer.stop();
			mediaPlayer.reset();
		}

		// Tell the user we stopped.
		Toast.makeText(this, R.string.reminder_service_finished, Toast.LENGTH_SHORT).show();
	}

	@Override
	public IBinder onBind(Intent intent)
	{
		return mBinder;
	}

	/**
	 * This is the object that receives interactions from clients. See
	 * RemoteService for a more complete example.
	 */
	private final IBinder mBinder = new Binder()
	{
		@Override
		protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException
		{
			return super.onTransact(code, data, reply, flags);
		}
	};
}
